<template>
  <div>
    <h3>用户名称：{{ gettokenuser.nickname }}</h3>
    <h3>用户id：{{ gettokenuser.userId }}</h3>
    <h3>用户分组：{{ gettokenuser.roles[0] }}</h3>
  </div>
  <el-button type="primary" @click="addItemHandler()"> 添加用户 </el-button>
  <div>
    <div class="search">
      <el-card>
        <el-form :inline="true" :model="searchParams" class="demo-form-inline">
          <el-form-item label="用户名称" style="height: 32px;">
            <el-input v-model="searchParams.keywords" placeholder="输入用户名称" clearable style="height: 32px;" />
          </el-form-item>
          <el-form-item label="开始时间">
            <el-date-picker v-model="searchParams.startDate" type="date" placeholder="选择时间" clearable
              format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker v-model="searchParams.endDate" type="date" placeholder="选择时间" clearable format="YYYY-MM-DD"
              value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getPageData">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <div class="mytable">
      <el-card>
        <el-table :data="tableData" style="width: 100%">
          <el-table-column fixed prop="id" label="用户ID" width="150" />
          <el-table-column prop="nickname" label="用户名称" width="120" />
          <el-table-column prop="username" label="用户" width="120" />
          <el-table-column prop="mobile" label="电话" width="120" />
          <el-table-column prop="status" label="用户状态" width="120" />
          <el-table-column prop="deptName" label="部门" width="120" />
          <el-table-column prop="createTime" label="更新时间" width="220" />

          <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="editItemHandler(row)">
                修改
              </el-button>
              <el-button link type="primary" size="small" @click="delItemHadler(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <div class="mypage">
      <el-pagination background layout="prev, pager, next" :total="pageParams.total" @change="pageChangeHandler" />
    </div>

    <el-dialog v-model="dialogFormVisible" :title="ruleFormInfo.title" width="800" style="width: 400px;">
      <UserForm ref="ruleFormRef" :form-data="ruleForm" :disabled="isSBtnDisable" :loading="isSBtnLoding"
        :submitForm="submitForm"></UserForm>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, useTemplateRef, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { isObject } from 'lodash'
import { addUser, deluser, editUser, getUser, tokenuser, type tokenuserType, type usersType, userInfo } from '@/views/jiekoutest/domo4'
import UserForm from './components/UserForm.vue'
import 'element-plus/theme-chalk/el-message.css'
import 'element-plus/theme-chalk/el-message-box.css'




const rrrr = userInfo(103)
console.log(rrrr, 'rrrr')









const tableData = ref<usersType[]>()
const dialogFormVisible = ref(false)
const isSBtnLoding = ref(false)
const isSBtnDisable = ref(false)
const ruleFormRef = useTemplateRef('ruleFormRef')

const pageParams = ref({
  pageNum: 1,
  pageSize: 100,
  total: 0
})

const searchParams = ref({
  keywords: '',
  startDate: '',
  endDate: ''
})


const ruleForm = ref<usersType>({
  username: "",
  nickname: "",
  email: "",
  gender: 0,
  password: "",
  mobile: "",
  id: 1,
  avatar: "http://dummyimage.com/100x100",
  status: 1,
  deptId: 1,
  roleIds: [
    1
  ]
})
const ruleFormInfo = ref<{ type: 'add' | 'edit'; title: string }>({
  type: 'add',
  title: '添加数据'
})

const submitForm = async (formEl: FormInstance | undefined) => {
  isSBtnLoding.value = true
  isSBtnDisable.value = true

  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res

      try {
        ruleForm.value.id = Number(ruleForm.value.id)
        if (ruleFormInfo.value.type === 'add') {
          res = await addUser(ruleForm.value)
        }
        if (ruleFormInfo.value.type === 'edit') {
          res = await editUser(ruleForm.value.id, ruleForm.value)
        }
        if (res!.code !== '2000') {
          throw new Error(isObject(res?.msg) ? (res.msg as { Message: string })?.Message : res?.msg)
        }
        ElMessage.success(ruleFormInfo.value.type === 'add' ? `添加成功` : `修改成功`)
        getPageData()
      } catch (error: any) {
        ElMessage.error(error.message)
      } finally {
        isSBtnLoding.value = false
        isSBtnDisable.value = false
        dialogFormVisible.value = false
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const getPageData = async () => {
  const resRoles = await getUser({
    pageNum: pageParams.value.pageNum,
    pageSize: pageParams.value.pageSize,
    ...searchParams.value
  })
  console.log(resRoles, 'resRoles')

  tableData.value = resRoles.data.list
  pageParams.value.total = resRoles.data.total
}

const addItemHandler = async () => {
  dialogFormVisible.value = true
  ruleForm.value = JSON.parse(
    JSON.stringify({
      username: "",
      nickname: "",
      email: "",
      gender: 1,
      password: "",
      mobile: "",
      id: null,
      avatar: "http://dummyimage.com/100x100",
      status: 1,
      deptId: 1,
      roleIds: [
        1
      ]
    })
  )

  ruleFormInfo.value = {
    type: 'add',
    title: '添加用户'
  }
  ruleFormRef.value?.reset()
}

const editItemHandler = (row: usersType) => {
  dialogFormVisible.value = true

  ruleFormInfo.value = {
    type: 'edit',
    title: '修改用户'
  }
  ruleForm.value = JSON.parse(JSON.stringify(row))
  ruleFormRef.value?.reset()
}

const delItemHadler = (row: usersType) => {
  ElMessageBox.confirm('确认删除?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await deluser(`${row.id}`)

        if (res.code !== '2000') {
          throw new Error(res.msg)
        }

        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        getPageData()
      } catch (error: any) {
        ElMessage({
          type: 'error',
          message: error.message
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

const gettokenuser = ref<tokenuserType>({
  userId: '',
  avatar: '',
  nickname: '',
  roles: ''
})
const tokengetuser = async () => {
  gettokenuser.value = ((await tokenuser()).data) as unknown as tokenuserType
  console.log((gettokenuser.value as unknown as tokenuserType))
}
const pageChangeHandler = (currentPage: number, pageSize: number) => {
  pageParams.value.pageNum = currentPage
  pageParams.value.pageSize = pageSize
  getPageData()
}

onMounted(() => {
  getPageData()
  tokengetuser()
})


</script>

<style lang="scss" scoped></style>
